package handler;

import http.MyHttpRequest;
import http.MyHttpResponse;
import http.four4xx.AuthenticationRequired;
import http.four4xx.NotFound;
import http.two2xx.FisherResponse;
import util.MyUtil;

import java.io.*;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author Karl
 * @Date 2023/1/3 - 21:25
 */
public class FilterHandler implements Handler {

    /**
     * 记录了从文件中读出来的需要过滤的域名或者IP
     */
    public static Map<String, String> filterSet = null;

    public static MyHttpResponse defaultResponse;

    public FilterHandler() {

        defaultResponse = new NotFound();
        filterSet = new HashMap<>();
        try {
            ResourceBundle bundle = ResourceBundle.getBundle("filter");
            Enumeration<String> keys = bundle.getKeys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                filterSet.put(key, bundle.getString(key));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private MyHttpResponse get404() {
        return defaultResponse;
    }

    /**
     * @param request 截取请求头
     * @param from    来源
     * @param to      远程服务器
     * @return 是否结束调用的进程
     */
    @Override
    public boolean handler(MyHttpRequest request, Socket from, Socket to) {
        try {
            OutputStream writer = from.getOutputStream();
            MyHttpResponse response = defaultResponse;
            switch (filterSet.getOrDefault(request.getHost(), "")) {
                case "fisher":
                    String[] split = request.getRequestLine().split(" ");
                    if (split[1].endsWith(request.getHost()) || split[1].endsWith(request.getHost() + "/")) {
                        response = checkFisher(request, request.getHost());
                    } else if (split[1].contains(request.getHost() + "/add")) {
                        System.out.println(new String(request.getRequestBody()));
                        response = defaultResponse;
                    }
                    break;
            }
            response.sendMessage(writer);
        } catch (IOException e) {
            MyUtil.log("exception : %s %s", e.getClass(), e.getLocalizedMessage());
            return true;
        }
        return false;
    }

    private MyHttpResponse checkFisher(MyHttpRequest request, String host) {
//        File file = new File( host + ".html");
        InputStream resource = null;
        try {
            resource = this.getClass().getClassLoader().getResourceAsStream(host + ".html");
            if(resource==null) return defaultResponse;
            return new FisherResponse(resource);

        } catch (Exception e) {
            e.printStackTrace();
            return defaultResponse;
        } finally {
            MyUtil.closeIo(resource);
        }
//        return defaultResponse;
    }

    @Override
    public boolean isSupport(MyHttpRequest request, Socket remote) {
        return filterSet.containsKey(request.getHost());
    }


}
